package com.neusoft.ysu.populationmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.neusoft.ysu.populationmanagement.constant.Errors;
import com.neusoft.ysu.populationmanagement.entity.CommonResult;
import com.neusoft.ysu.populationmanagement.entity.IdnumSequence;
import com.neusoft.ysu.populationmanagement.mapper.IdnumSequenceMapper;
import com.neusoft.ysu.populationmanagement.service.IIdnumSequenceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者：张幸晔
 * @since 2024-06-20
 */
@Service
public class IdnumSequenceServiceImpl implements IIdnumSequenceService {
    @Autowired
    private IdnumSequenceMapper idnumSequenceMapper;
    /**
     * @author 张幸晔
     * @date 2024-06-20 14:32
     * @param district
     * @param genderId
     * @return java.lang.String
     */

    @Override
    public String selectIdNumSequence(String district, Integer genderId) {
        LambdaQueryWrapper<IdnumSequence> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaUpdateWrapper<IdnumSequence> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //查找sql
        lambdaQueryWrapper.eq(IdnumSequence::getDistrict,district);
        //更新sql
        lambdaUpdateWrapper.eq(IdnumSequence::getDistrict,district);
        List<IdnumSequence> idnumSequences = idnumSequenceMapper.selectList(lambdaQueryWrapper);
        IdnumSequence idnumSequence= new IdnumSequence();
        String sequence = "";
        String newSequence = "";
        if (genderId==1){//男，取当前顺序号返回，并加+2保存
            sequence = idnumSequences.get(0).getManSequence();
            newSequence = String.format("%03d",(Integer.parseInt(sequence)+2));
            idnumSequence.setManSequence(newSequence);
            idnumSequenceMapper.update(idnumSequence,lambdaUpdateWrapper);
        }else{//女同样操作
            sequence = idnumSequences.get(0).getWomanSequence();
            newSequence = String.format("%03d",(Integer.parseInt(sequence)+2));
            idnumSequence.setWomanSequence(newSequence);
            idnumSequenceMapper.update(idnumSequence,lambdaUpdateWrapper);
        }
        return sequence;
    }

    @Override
    public CommonResult resetSequence() {
        IdnumSequence idnumSequence = new IdnumSequence();
        idnumSequence.setManSequence("001");
        idnumSequence.setWomanSequence("002");
        int rows = idnumSequenceMapper.update(idnumSequence,null);
        if (rows <=0){
            return new CommonResult<>(Errors.ERROR,"重置失败",null);
        }
        return new CommonResult<>(Errors.SUCCESS,"重置成功",null);
    }
}
